package springboot1706.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.impl.DefaultKaptcha;

import springboot1706.util.RedisUtil;

@Controller
public class TestController {
	Logger log = LoggerFactory.getLogger(TestController.class);
	@Resource
	RedisUtil redisUtil;
	@Resource
	private DefaultKaptcha captchaProducer;
	@Resource
	private JavaMailSender mailSender;
	
	
	
	@RequestMapping("/defaultKaptcha")  
    public void defaultKaptcha(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) throws Exception{  
            byte[] captchaChallengeAsJpeg = null;    
             ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();    
             try {    
             //生产验证码字符串并保存到session中  
             String createText = captchaProducer.createText();  
             httpServletRequest.getSession().setAttribute("vrifyCode", createText);  
             //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中  
             BufferedImage challenge = captchaProducer.createImage(createText);  
             ImageIO.write(challenge, "jpg", jpegOutputStream);  
             } catch (IllegalArgumentException e) {    
                 httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);    
                 return;    
             }   

             //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组  
             captchaChallengeAsJpeg = jpegOutputStream.toByteArray();    
             httpServletResponse.setHeader("Cache-Control", "no-store");    
             httpServletResponse.setHeader("Pragma", "no-cache");    
             httpServletResponse.setDateHeader("Expires", 0);    
             httpServletResponse.setContentType("image/jpeg");    
             ServletOutputStream responseOutputStream =    
                     httpServletResponse.getOutputStream();    
             responseOutputStream.write(captchaChallengeAsJpeg);    
             responseOutputStream.flush();    
             responseOutputStream.close();    
    }
	
	  /**
     * 验证的方法
     * @param req
     * @param res
     * @return
     */
	@RequestMapping("/imgvrifyControllerDefaultKaptcha")
    public String imgvrifyControllerDefaultKaptcha(HttpServletRequest req,HttpServletResponse res, Model model){  
         String captchaId = (String) req.getSession().getAttribute("vrifyCode");    
         String parameter = req.getParameter("vrifyCode");  
         System.out.println("Session  vrifyCode "+captchaId+" form vrifyCode "+parameter);  

        if (captchaId==null || !captchaId.equals(parameter)) {  
            model.addAttribute("username", "错误的验证码");  
        } else {  
        	model.addAttribute("username", "正确的验证码");  
        	SimpleMailMessage message = new SimpleMailMessage();
    		message.setFrom("1363378049@qq.com");
    		message.setTo("1192420306@qq.com");
    		message.setSubject("主题：简单邮件");
    		message.setText("测试邮件内容");
    		mailSender.send(message);

        }  
        return "test2";  
    }

	
	
	
	
	@RequestMapping("test")
	@ResponseBody
	public String test() {
		return "test";
	}
	@RequestMapping("test2")
	public String test2(String username, Model model) {
		model.addAttribute("username", username);
		if("root".equals(username))
			throw new RuntimeException("测试异常");

		return "test2";
	}
	@RequestMapping("test3")
	public String test3(Model model) {
		String key = "key";
		String val = "root";
		if(redisUtil.exists(key)) {
			model.addAttribute("username", redisUtil.get(key));
		} else {
			redisUtil.set(key, val);
		}
		return "test2";
	}	
}
